<template lang="">
    <div class="withdrawal">
        <div>
            <a-typography-title type="secondary" :level="4" style="color: #3677fc;font-size:18px">
                {{ $t('keQu', [userWalletBalance]) }} 
                <a-button type="primary" shape="circle" :loading="loading" @click="fetchCashWithdrawalInfo">
                    <template #icon><redo-outlined /></template>
                </a-button>
            </a-typography-title>
        </div>

        <div style="width: 500px;margin: 15px 0;">
            <a-steps :current="current" size="small">
                <a-step v-for="item in steps" :key="item.key" :title="item.title"  :disabled="true"/>
            </a-steps>
        </div>

        <div class="steps-content">
            <a-form
                :model="formState"
                name="time_related_controls"
                v-bind="formItemLayout"
                @finish="onFinish"
                @finishFailed="onFinishFailed"
            >
                <a-form-item 
                    name="client_bankcard_id" 
                    :label="$t('xuan-4')" 
                    :rules="[{ required: true, message: '请选择银行!' }]"
                >
                    <a-select 
                        v-model:value="formState.client_bankcard_id" 
                        style="width: 200px"  
                        size="large"
                        @change="onBankSelectChange">
                        <a-select-opt-group 
                            :label="$t('xuNi-1')"
                            v-if="userUSDTList.length > 0"
                        >
                            <a-select-option 
                             v-for="(item, index) in userUSDTList"
                             :key="'user-usdt-item' + index"
                             :value="item.id"
                            >{{ item.bank_name }}</a-select-option>
                        </a-select-opt-group>

                        <a-select-opt-group 
                            :label="$t('yinH')"
                            v-if="userBankCardList.length > 0"
                        >
                            <a-select-option 
                             v-for="(item, index) in userBankCardList"
                             :key="'user-bank-item' + index"
                             :value="item.id"
                            >{{ item.bank_name }}</a-select-option>
                        </a-select-opt-group>
                    </a-select>
                </a-form-item>
        
        
                <a-form-item 
                    name="amount" 
                    :label="$t('quKu-2')"
                    :rules="amountRule"
                >
                    <a-input-number v-model:value="formState.amount" :min="200" size="large" style="width: 240px"/>
                </a-form-item>
        
                <div >
                    <h4>{{ $t('wenX-1') }}</h4>
                    <ul>
                        <li v-if="hasUSDT" style="color: red">{{ $t('huiS') }}</li>
                        <li>{{ $t('danB-0') }}</li>
                        <li>{{ $t('quKu-3') }}</li>
                        <li>{{ $t('usdt') }}</li>
                    </ul>
                </div>

                <a-form-item
                    :wrapper-col="{
                        xs: { span: 24, offset: 0 },
                        sm: { span: 16, offset: 8 },
                    }"
                >
                    <a-button 
                        :loading="loading"
                        :disabled="hasDisable" 
                        type="primary" 
                        html-type="submit" 
                        size="large" 
                        style="width: 200px">{{ $t('xiaY') }}</a-button>
                </a-form-item>
            </a-form>
        </div>
  
        <UsdtDepositModal 
            :paymentId="curPaymentId" 
            :depositSettingId="curDepositSettingId"
            :rechargeAmount="curRechargeAmount" 
            :visible="modalVisible" 
            @cancel="modalVisible=false" 
            @ok="gotoDepositRecord" 
        />
    </div>
</template>
<script setup lang="ts">
import { createApplicationForWithdrawal, getCashWithdrawalInfo, getUserBankCardList } from '@/api/financial';
import { ref, onBeforeMount } from 'vue';
import UsdtDepositModal from '@/components/UsdtDepositModal/UsdtDepositModal.vue';
import { useRouter } from 'vue-router'
import { formatCurrency } from '@/utils'
import { RedoOutlined } from '@ant-design/icons-vue';
import { walletTransfer } from '../../../api/financial';
import { Modal, message } from 'ant-design-vue';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const router = useRouter();
const userAccountList = ref<any[]>([]);
const userBankCardList = ref<any[]>([]);
const userUSDTList = ref<any[]>([]);
const userWalletBalance = ref<number>(0);

const hasUSDT = ref<boolean>(false);
const loading = ref<boolean>(false);
const singleMinAmount = ref<string>('');
const singleMaxAmount = ref<string>('');
const hasDisable = ref<boolean>(false);

const curPaymentId = ref('');
const curDepositSettingId = ref('');
const curRechargeAmount = ref('');
const modalVisible = ref<boolean>(false);
const current = ref<number>(0);
const steps = [
    {
        key: 'submit',
        title: t('1Ti'),
        content: 'First-content',
    },
    {
        key: 'review',
        title: t('2She'),
        content: 'Second-content',
    },
    {
        key: 'dispensing',
        title: t('3Chu'),
        content: 'Last-content',
    },
    {
        key: 'account',
        title: t('4Dao'),
        content: 'sLast-content',
    },
]
const emit = defineEmits(["switch"]);

const formItemLayout = {
    labelCol: {
        xs: { span: 3 },
        sm: { span: 3 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
    },
};

const amountRule = [
    {
        validator: (_: any, value: number) =>
        new Promise((resolve, reject) => {
            if (value <= 0) {
                // 任意渠道，都不允许输入0及以下的金额
                reject(t('qing-19'));
            } else {
                // 从平台转出
                if (value > userWalletBalance.value) {
                    reject(t('chao-1'));
                } else {
                    resolve(value);
                }
            }
        })
    }
]

interface FormState {
    "client_bankcard_id": string;
    'amount': string;
}
const formState = reactive({
    client_bankcard_id: '',
    amount: ''
} as FormState);


const onFinish = (values: any) => {
    console.log('Success:', values, formState);
    const { client_bankcard_id, amount } = values;

    if (
        client_bankcard_id
        && amount
    ) {
        loading.value = true;
        createApplicationForWithdrawal({
            client_bankcard_id,
            amount
        }).then((res: any) => {
            const { status } = res;
            if (status === 'OK') {
                message.success(t('caoZ-3'));
            } else {
                message.error(t('tiJi'));
            }
        }).catch((err: any) => {
            message.error(t('tiJi-0'));
        }).finally(() => {
            loading.value = false;
        });
    }

};

const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
};

function gotoDepositRecord() {
    modalVisible.value = false
    emit('switch', '2');
}

function onBankSelectChange(id: string) {
    const curItem = userAccountList.value.find((item: any) => item.id == id);
    if (curItem) {
        hasUSDT.value = curItem.bank_type === 1
    }
}

function fetchCashWithdrawalInfo() {
    loading.value = true;
    getCashWithdrawalInfo()
        .then((res: any) => {
            const { info, WithdrawalLimit } = res;
            if (info) {
                if (info.wallet_balance) {
                    userWalletBalance.value = info.wallet_balance;
                }
                
                // 未设置取款密码
                if (!info.withdrawal_password) {
                    Modal.confirm({
                        title: t('tiSh-0'),
                        content: t('zhang-2'),
                        okText: t('haoD'),
                        cancelText: t('quXi'),
                        onOk() {
                            router.push({ name: 'WithdrawalsPassword' })
                        }
                    });
                    hasDisable.value = true;
                }
            }

            if (WithdrawalLimit) {
                singleMinAmount.value = formatCurrency(WithdrawalLimit.single_min_amount || '200');
                singleMaxAmount.value = formatCurrency(WithdrawalLimit.single_max_amount || '50000');
            }
        })
        .catch((err: any) => {
            console.log(err)
        }).finally(() => {
            loading.value = false;
        });
}

function fetchuserAccountList() {
    getUserBankCardList()
    .then((res: any) => {
        const list = res.list || [];
        if (Array.isArray(list) && list.length > 0) {
            userAccountList.value = list;
            userBankCardList.value = list.filter((item) => item.bank_type === 2);
            userUSDTList.value = list.filter((item) => item.bank_type === 1);
        } else {
            // 未添加银行卡
            Modal.confirm({
                title: t('tiSh-0'),
                content: '当前尚未绑定银行账号，是否现在去添加？',
                okText: t('haoD'),
                cancelText: t('quXi'),
                onOk() {
                    router.push({ name: 'brankCard' })
                }
            });
            hasDisable.value = true;
        }
    })
}

onBeforeMount(() => {
    fetchuserAccountList();
    fetchCashWithdrawalInfo();
})

</script>
  
<style lang="less" scoped>
.pay-radio {
    margin-bottom: 10px;
    margin-right: 10px;
    height: 40px;
    line-height: 40px;

    img {
        height: 28px;
        margin-right: 5px;
    }
}

.payment-method-radio {
    padding-top: 5px;
    padding-bottom: 5px;
    height: 55px;

    p {
        line-height: 1.5;
    }
}
</style>